import 'package:adb_tool/base/base_page_state.dart';
import 'package:adb_tool/page/home/home_view_model.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../common/app_color.dart';
import 'menu_model.dart';

class HomePage extends StatefulWidget {
  final String deviceId;
  final String packageName;

  const HomePage({Key? key, required this.deviceId, required this.packageName}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends BasePageState<HomePage, HomeViewModel> {
  @override
  void initState() {
    super.initState();
  }

  @override
  buildContentView(BuildContext context) {
    return DropTarget(
      child: Container(
        color: AppColors.white,
        margin: const EdgeInsets.symmetric(horizontal: 12),
        child: SingleChildScrollView(
          child: Column(
            children: [
              _buildMenuTitle(title: "应用相关"),
              _buildMenu(list: viewModel.categoryApps, crossAxisCount: 3),
              _buildMenuTitle(title: "系统相关"),
              _buildMenu(list: viewModel.categorySystems, crossAxisCount: 3),
              _buildMenuTitle(title: "按键相关"),
              _buildMenu(list: viewModel.categoryActions, crossAxisCount: 4)
            ],
          ),
        ),
      ),
      onDragDone: (details) {
        viewModel.onDragDone(details);
      },
    );
  }

  @override
  HomeViewModel createViewModel() {
    return HomeViewModel(context, widget.deviceId, widget.packageName);
  }

  /// 菜单的点击事件
  _handleClick(String id) async {
    switch (id) {

      /// 安装app
      case "installApp":
        viewModel.install();
        break;

      /// 卸载app
      case "unInstallApp":
        viewModel.uninstallApk();
        break;

      /// 启动app
      case "startApp":
        viewModel.startApp();
        break;

      /// 停止app
      case "stopApp":
        viewModel.stopApp();
        break;

      /// 重启应用
      case "rebootApp":
        viewModel.restartApp();
        break;

      /// 清除数据
      case "clearData":
        viewModel.clearAppData();
        break;

      /// 清除数据并重启应用
      case "clearDataAndRebootApp":
        await viewModel.clearAppData();
        await viewModel.startApp();
        break;

      /// 重置权限
      case "resetPermissions":
        viewModel.resetAppPermission();
        break;

      /// 重置权限并重启应用
      case "resetPermissionsReboot":
        await viewModel.stopApp(isShowResult: false);
        await viewModel.resetAppPermission();
        await viewModel.startApp();
        break;

      /// 授予所有权限
      case "setAllPermissions":
        viewModel.grantAppPermission();
        break;

      /// 查看应用安装路径
      case "viewInstallPath":
        viewModel.getAppInstallPath();
        break;

      /// 屏幕截图
      case "screenshotToPc":
        viewModel.screenshot();
        break;

      /// 开启录屏
      case "screenRecord":
        viewModel.startScreenRecord();
        break;

      /// 停止录屏
      case "stopScreenRecord":
        viewModel.stopRecordAndSave();
        break;

      /// 查看当前activity
      case "viewCurrentActivity":
        viewModel.getAppInstallPath();
        break;

      /// 查看Android ID
      case "viewApplicationId":
        viewModel.getAndroidId();
        break;

      /// 查看android系统版本
      case "viewAndroidVersion":
        viewModel.getDeviceVersion();
        break;

      /// 查看本地手机ip
      case "viewLocalIdAddress":
        viewModel.getDeviceIpAddress();
        break;

      /// 查看本地mac 地址
      case "viewLocalMacAddress":
        viewModel.getDeviceMac();
        break;

      /// 重启设备
      case "rebootDevice":
        viewModel.reboot();
        break;
    /// 返回键
      case "backKeyword":
        viewModel.reboot();
        break;
    /// home键
      case "homeKeyword":
        viewModel.pressHome();
        break;
    /// 菜单键
      case "menuKeyword":
        viewModel.pressMenu();
        break;
    /// 电源键
      case "powerKeyword":
        viewModel.pressPower();
        break;
    /// 增加音量
      case "volumeUpKeyword":
        viewModel.pressVolumeUp();
        break;
    /// 减低音量
      case "volumeDownKeyword":
        viewModel.pressVolumeDown();
        break;
    /// 静音
      case "volumeMuteKeyword":
        viewModel.pressVolumeMute();
        break;
    /// 切换应用
      case "switchAppKeyword":
        viewModel.pressSwitchApp();
        break;
    }
  }

  _buildMenuTitle({required String title}) {
    return Container(
      alignment: Alignment.centerLeft,
      margin: const EdgeInsets.only(top: 14, bottom: 8),
      child: Text(
        title + ":",
        style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: AppColors.c33),
      ),
    );
  }

  _buildMenu({required List<MenuModel> list, int crossAxisCount = 3}) {
    return Consumer<HomeViewModel>(builder: (context, value, child) {
      return GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              mainAxisSpacing: 8,
              crossAxisCount: crossAxisCount,
              mainAxisExtent: 48,
              childAspectRatio: 0.1,
              crossAxisSpacing: 8.0),
          itemCount: list.length,
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          scrollDirection: Axis.vertical,
          itemBuilder: (context, index) {
            var item = list[index];
            return item.id == "screenRecord"
                ? ElevatedButton(
                    onPressed: () {
                      _handleClick(item.id);
                    },
                    style: ButtonStyle(backgroundColor: MaterialStateProperty.all(AppColors.primary)),
                    child: SizedBox(
                      width: double.infinity,
                      child: Center(
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(value.isRecording ? Icons.stop_sharp : Icons.play_arrow_sharp),
                            Text(
                              value.isRecording ? "录屏进行中.." : "开始录屏",
                              style: const TextStyle(fontSize: 14, color: AppColors.white),
                            ),
                            value.isRecording
                                ? const SizedBox(
                              width: 16,
                                    height: 16,
                                    child: CircularProgressIndicator(
                                      color: AppColors.white,
                                    ),
                                  )
                                : const SizedBox()
                          ],
                        ),
                      ),
                    ))
                : ElevatedButton(
                    onPressed: () {
                      _handleClick(item.id);
                    },
                    style: ButtonStyle(backgroundColor: MaterialStateProperty.all(AppColors.primary)),
                    child: SizedBox(
                      width: double.infinity,
                      child: Center(
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              item.label,
                              style: const TextStyle(fontSize: 14, color: AppColors.white),
                            ),
                            item.hasChoose ? const Icon(Icons.arrow_drop_down) : const SizedBox()
                          ],
                        ),
                      ),
                    ));
          });
    });
  }
}
